package cn.trigram;

import java.lang.instrument.Instrumentation;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

public class FakeTimeAgent {

  public static void premain(String agentArgs, Instrumentation inst) {

    if (Objects.isNull(agentArgs) || agentArgs.trim().length() <= 0) {
      return;
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    long             timestamp;
    try {
      Date date = simpleDateFormat.parse(agentArgs);
      timestamp = date.getTime();
    } catch (ParseException e) {
      System.err.println("日期格式错误");
      return;
    }

    inst.addTransformer((loader, className, classBeingRedefined, protectionDomain, classfileBuffer) -> {

      //（1）构建ClassReader
      ClassReader cr = new ClassReader(classfileBuffer);

      //（2）构建ClassWriter
      ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);

      //（3）串连ClassVisitor
      ClassVisitor cv = new MethodReplaceInvokeVisitor(cw, timestamp);

      //（4）结合Cla***eader和ClassVisitor
      int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
      cr.accept(cv, parsingOptions);

      //（5）生成byte[]
      return cw.toByteArray();
    });
  }

}
